#!/usr/bin/python3
import io
import json

from sklearn.externals import joblib
from process.cv_process import CVPorcess
from werkzeug.routing import BaseConverter

from flask import Flask, render_template, request, send_file, Response, jsonify

# app = Flask(__name__, static_url_path='', root_path='')
app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')
    # return 'hello'

@app.errorhandler(404)
def internal_server_error(e):
    return '服务器搬家了'

@app.route('/uploadimg', methods=['POST'])
def img():
    img = request.files.get("file")
    with open('process/get_img.jpg', 'wb') as f:
        f.write(img.read())

    #  图像处理
    cvp = CVPorcess()
    filename = cvp.extractP('./process/get_img.jpg')
    return filename

@app.route('/splitimg', methods=['GET'])
def split_img():
    img_name = request.args.get('name')
    print(img_name)
    if img_name is '':
        return '解析错误'

    cvp = CVPorcess()
    # filename提取的车牌数字图片
    img_end_list, gray_end_list, filename = cvp.split_img('static/results/%s'%img_name, img_name)
    print('imglist')
    if img_end_list is None:
        data = {'Result': '解析错误', 'filename': filename}

        return json.dumps(data)

    # 机器学习
    model = joblib.load("process/test.pkl")
    y_predict = model.predict(gray_end_list)
    # print("预测结果为:\n", y_predict)
    folder_list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                   'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
                   'W', 'X', 'Y', 'Z',
                   '云', '京', '冀', '吉', '宁', '川', '新', '晋', '桂', '沪', '津', '浙', '渝', '湘', '琼', '甘', '皖', '粤', '苏', '蒙',
                   '藏', '豫', '贵', '赣', '辽', '鄂', '闽', '陕', '青', '鲁', '黑']
    k = []
    for i in y_predict:
        k.append(folder_list[i])
    data = {'Result': k, 'filename': filename}

    return json.dumps(data)

if __name__ == '__main__':
    print(app.url_map)
    app.run(host="127.0.0.1", port=5000, debug = True)
